<?

function html_attributes($attributes) {
    if ($attributes) {
        $html_attributes = '';
        foreach ($attributes as $attr_name => $attr_value):
            $html_attributes .= "$attr_name=\"$attr_value\" ";
        endforeach;
        return $html_attributes;
    }
    return '';
}

function url($controller, $method = 'index', $args = array()) {
    $url = implode('/', array_merge(array($controller, $method), $args));
    return BASE_URL . $url;
}

function link_to($text, $controller, $method = 'index', $args = array(), $html = array()) {
    return '<a href="' . url($controller, $method, $args) . '"' . html_attributes($html) . '>' . $text . '</a>';
}

function get_url($controller, $method, $args = array()) {
    $url_components = array_merge(array($controller, $method), $args);
    return BASE_URL . implode("/", $url_components);
}

function redirect_to($controller, $method = '', $args = array()) {
    header('location:' . get_url($controller, $method, $args));
}

function show_errors($errors) {
    if ($errors):
        $errors_html = '<ul class="errors">';
        foreach ($errors as $name => $error):
            $errors_html .= "<li>$error</li>";
        endforeach;
        $errors_html .= '</ul>';
        return $errors_html;
    endif;
    return '';
}

function select_tag($params) {
    $select = "<select " . html_attributes($params['html_options']) . ">";
    if ($params['empty_option'])
        $select .= '<option></option>';
    foreach ($params['collection'] as $object):
        $value = $object->read_attribute($params['value']);
        $attribute_to_show = $object->read_attribute($params['show']);
        $select .= "<option value='{$value}' ";
        $select .= ($params['selected_value'] && $params['selected_value'] == $value) ? "selected>" : ">";
        $select .= "$attribute_to_show</option>";
        endforeach;
    $select .= '</select>';
    return $select;
}

?>
